<?php


namespace GordenSong\Templates;


use GordenSong\Exceptions\TableNotExistException;
use GordenSong\Utils\PathUtil;
use GordenSong\Utils\TableMeta;

class TableValidatorCacheTemplate extends AbstractTemplate
{
	const DIRNAME = 'table-validator';

	/** @var string */
	private $bladeFile;
	/** @var string */
	private $targetFile;
	/** @var string|null */
	private $connectionName;
	/** @var string */
	private $table;

	public function __construct(string $connectionName, string $table)
	{
		$this->connectionName = $connectionName;
		$this->table = $table;
	}

	public function bladeFile(): string
	{
		if (empty($this->bladeFile)) {
			$php = __DIR__ . '/../../resources/views/table-validator-config.blade.php';

			$this->bladeFile = PathUtil::crossPlatformPath($php);
		}
		return $this->bladeFile;
	}

	public static function defaultCachePath(): string
	{
		return app()->bootstrapPath() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . self::DIRNAME;
	}

	public static function configCachePath(): ?string
	{
		return config(self::DIRNAME . '.cache.path');
	}

	public static function cachePath(): string
	{
		return self::configCachePath() ?: self::defaultCachePath();
	}

	public function targetFile(): string
	{
		if (empty($this->targetFile)) {
			$this->targetFile = self::cachePath() . DIRECTORY_SEPARATOR . $this->connectionName . DIRECTORY_SEPARATOR . $this->table . '.php';
		}
		return $this->targetFile;
	}

	/**
	 * @return array
	 * @throws \Doctrine\DBAL\Schema\SchemaException
	 * @throws \GordenSong\Exceptions\TableNotExistException
	 */
	public function getCompiledData(): array
	{
		$tableMeta = TableMeta::make($this->connectionName, $this->table);

		return [
			'rules' => $tableMeta->getRules()
		];
	}
}
